/**
 * Project Name:dsrs-systemservice-web
 * File Name:UserLevelController.java
 * Package Name:com.bwda.dsrs.systemservice.controller;
 * Date:2019年4月28日
 * Copyright (c) 2019, 江苏保旺达软件有限公司 All Rights Reserved.
 */
package com.bwda.dsrs.systemservice.controller;


import com.bwda.dsrs.base.centerbase.response.CentreCutPageResponse;
import com.bwda.dsrs.base.centerbase.response.CentreListResponse;
import com.bwda.dsrs.base.centerbase.response.ResponseEntity;
import com.bwda.dsrs.base.util.CopyUtil;
import com.bwda.dsrs.systemservice.annotations.NeedRole;
import com.bwda.dsrs.systemservice.aspect.LogTypeEnum;
import com.bwda.dsrs.systemservice.aspect.Loggable;
import com.bwda.dsrs.systemservice.domain.Constants;
import com.bwda.dsrs.systemservice.domain.condition.datadict.DatadictCondition;
import com.bwda.dsrs.systemservice.domain.condition.user.UserCondition;
import com.bwda.dsrs.systemservice.domain.condition.userlevel.UserLevelCondition;
import com.bwda.dsrs.systemservice.domain.exception.SystemServiceException;
import com.bwda.dsrs.systemservice.domain.form.user.UserChangeLevelForm;
import com.bwda.dsrs.systemservice.domain.form.user.UserForm;
import com.bwda.dsrs.systemservice.domain.form.user.UserQueryForm;
import com.bwda.dsrs.systemservice.domain.form.userlevel.UserLevelBindUserForm;
import com.bwda.dsrs.systemservice.domain.form.userlevel.UserLevelCreateForm;
import com.bwda.dsrs.systemservice.domain.form.userlevel.UserLevelQueryForm;
import com.bwda.dsrs.systemservice.domain.form.userlevel.UserLevelUpdateForm;
import com.bwda.dsrs.systemservice.domain.po.datadict.DatadictPo;
import com.bwda.dsrs.systemservice.domain.po.role.UserByRolePo;
import com.bwda.dsrs.systemservice.domain.po.user.UserPo;
import com.bwda.dsrs.systemservice.domain.po.userlevel.UserLevelPo;
import com.bwda.dsrs.systemservice.domain.vo.userlevel.UserLevelTypeValueVo;
import com.bwda.dsrs.systemservice.domain.vo.userlevel.UserLevelTypeVo;
import com.bwda.dsrs.systemservice.domain.vo.userlevel.UserLevelVo;
import com.bwda.dsrs.systemservice.service.DatadictService;
import com.bwda.dsrs.systemservice.service.UserLevelService;
import com.bwda.dsrs.systemservice.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户等级
 *
 * @author liangjianyong
 * @date 2019/4/27
 */
@RestController
@RequestMapping("/s/userlevel")
@Api(value = "/s/userlevel", tags = "用户等级")
public class UserLevelController extends BaseController {

    @Autowired
    private UserLevelService userLevelService;

    @Autowired
    private UserService userService;

    @Autowired
    private DatadictService datadictService;

    @ApiOperation(value = "查询用户等级", notes = "查询用户等级", httpMethod = "GET")
    @Loggable(descp = "查询用户等级", type = LogTypeEnum.QUERY, include = "")
    @RequestMapping(value = "/query", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<UserLevelVo> query(@ApiParam(value = "等级ID", required = true) @RequestParam Integer id) throws SystemServiceException {
        UserLevelPo po = userLevelService.queryWithValid(id);
        UserLevelVo vo = CopyUtil.transfer(po, UserLevelVo.class);
        return getSuccessResult(vo);
    }

    @ApiOperation(value = "查询用户等级数量", notes = "查询用户等级数量", httpMethod = "GET")
    @Loggable(descp = "查询用户等级数量", type = LogTypeEnum.QUERY, include = "")
    @RequestMapping(value = "/queryCount", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<Integer> queryCount(@ModelAttribute @Valid UserLevelQueryForm form) throws SystemServiceException {
        UserLevelCondition condition = this.getConditionByQueryForm(form);
        int count = userLevelService.queryCount(condition);
        return getSuccessResult(count);
    }

    @ApiOperation(value = "查询当前组织下用户列表", notes = "查询当前组织下用户列表", httpMethod = "GET")
    @Loggable(descp = "查询当前组织下用户列表", type = LogTypeEnum.QUERY, include = "")
    @RequestMapping(value = "/queryUserByIncludeLevel", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<CentreCutPageResponse<UserByRolePo>> queryUserByIncludeLevel(@ModelAttribute @Valid UserQueryForm form) throws SystemServiceException {
        UserCondition condition = CopyUtil.transfer(form, UserCondition.class);
        int count = userService.queryUserByIncludeLevelCount(condition);
        List<UserByRolePo> poList = new ArrayList<>();
        if (count > 0) {
            poList = userService.queryUserByIncludeLevel(condition);
        }
        return getSuccessResult(getPageResponse(form, count, poList));
    }

    @ApiOperation(value = "查询用户等级列表", notes = "查询用户等级列表", httpMethod = "GET")
    @Loggable(descp = "查询用户等级列表", type = LogTypeEnum.QUERY, include = "")
    @RequestMapping(value = "/queryList", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<CentreListResponse<UserLevelVo>> queryList(@ModelAttribute @Valid UserLevelQueryForm form) throws SystemServiceException {
        UserLevelCondition condition = this.getConditionByQueryForm(form);
        List<UserLevelPo> poList = userLevelService.queryList(condition);
        List<UserLevelVo> voList = CopyUtil.transfer(poList, UserLevelVo.class);
        return getSuccessResult(getListResponse(voList));
    }

    @ApiOperation(value = "查询用户等级列表", notes = "查询用户等级列表", httpMethod = "GET")
    @Loggable(descp = "查询用户等级列表", type = LogTypeEnum.QUERY, include = "")
    @RequestMapping(value = "/queryListForLevelScore", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<CentreListResponse<UserPo>> queryListForLevelScore(@ModelAttribute @Valid UserLevelQueryForm form) throws SystemServiceException {
        UserCondition condition = new UserCondition();
        condition.setUserLevel(form.getLevelScore());
        condition.setDelFlag(Constants.NOT_DELETED);
        List<UserPo> poList = userService.selectListForLevelScore(condition);
        return getSuccessResult(getListResponse(poList));
    }

    @ApiOperation(value = "查询用户等级接口", notes = "查询用户等级接口", httpMethod = "GET")
    @Loggable(descp = "查询用户等级接口", type = LogTypeEnum.QUERY, include = "")
    @RequestMapping(value = "/queryUserLevelList", method = {RequestMethod.GET, RequestMethod.POST})
    public List<UserLevelPo> queryUserLevelList() throws SystemServiceException {
        UserLevelCondition userLevelCondition = new UserLevelCondition();
        userLevelCondition.setDelFlag(Constants.NOT_DELETED);
        List<UserLevelPo> poList = userLevelService.queryList(userLevelCondition);
        return poList;
    }

    @ApiOperation(value = "查询用户等级列表(带分页)", notes = "查询用户等级列表(带分页)", httpMethod = "GET")
    @Loggable(descp = "查询用户等级列表(带分页)", type = LogTypeEnum.QUERY, include = "")
    @RequestMapping(value = "/queryPageList", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<CentreCutPageResponse<UserLevelVo>> queryPageList(@ModelAttribute @Valid UserLevelQueryForm form) throws SystemServiceException {
        UserLevelCondition condition = this.getConditionByQueryForm(form);
        List<UserLevelVo> voList = new ArrayList<>();
        int count = userLevelService.queryCount(condition);
        if (count > 0) {
            List<UserLevelPo> poList = userLevelService.queryListWithTypeName(condition);
            voList = CopyUtil.transfer(poList, UserLevelVo.class);
        }
        return getSuccessResult(getPageResponse(form, count, voList));
    }
    @NeedRole("sysadminrole")
    @ApiOperation(value = "新增用户等级", notes = "新增用户等级", httpMethod = "POST")
    @Loggable(descp = "新增用户等级", type = LogTypeEnum.CREATE, include = "")
    @RequestMapping(value = "/add", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<UserLevelVo> add(@ModelAttribute @Valid UserLevelCreateForm form, HttpServletRequest request) throws SystemServiceException {
        UserLevelPo po = CopyUtil.transfer(form, UserLevelPo.class);
        String createUserCode = getUserCode();
        po.setCreateUserCode(createUserCode);
        //装载变量condition
        UserLevelCondition condition = CopyUtil.transfer(form, UserLevelCondition.class);
        condition.setDelFlag(Constants.NOT_DELETED);
        //判断此类型下是否存在相同的等级
        int count1 = userLevelService.countIsExist(condition);
        if (count1 != 0) {
            return getFailResult("此类型已经存在此等级");
        }
        userLevelService.insert(po);
        UserLevelVo vo = CopyUtil.transfer(po, UserLevelVo.class);
        return getSuccessResult(vo);
    }
    @NeedRole("sysadminrole")
    @SuppressWarnings("AlibabaRemoveCommentedCode")
    @ApiOperation(value = "修改用户等级", notes = "修改用户等级", httpMethod = "POST")
    @Loggable(descp = "修改用户等级", type = LogTypeEnum.UPDATE, include = "")
    @RequestMapping(value = "/update", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity update(@ModelAttribute @Valid UserLevelUpdateForm form, HttpServletRequest request) throws SystemServiceException {
        if (form.getId() == null) {
            return getFailResult("用户等级ID不能为空");
        }
        //修改用户分级记录
        UserLevelPo po = CopyUtil.transfer(form, UserLevelPo.class);
        String updateUserCode = getUserCode();
        po.setUpdateUserCode(updateUserCode);
        UserLevelCondition condition = CopyUtil.transfer(form, UserLevelCondition.class);
        condition.setDelFlag(Constants.NOT_DELETED);
        //判断此类型下是否存在相同的等级
        int count1 = userLevelService.countIsExist(condition);
        if (count1 != 0) {
            return getFailResult("此类型已经存在此等级");
        }
        userLevelService.update(po);
        return getSuccessResult();
    }
    @NeedRole("sysadminrole")
    @ApiOperation(value = "删除用户等级", notes = "删除用户等级", httpMethod = "POST")
    @Loggable(descp = "删除用户等级", type = LogTypeEnum.DELETE, include = "")
    @RequestMapping(value = "/delete", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity delete(@Valid @RequestParam(value = "id") List<Integer> id) throws SystemServiceException {
        if (id == null || id.size() == 0) {
            return getFailResult("参数错误");
        }
        userLevelService.batchDelete(id);
        return getSuccessResult();
    }

    @ApiOperation(value = "查询分级类型列表", notes = "查询分级类型列表", httpMethod = "POST")
    @Loggable(descp = "查询分级类型列表", type = LogTypeEnum.QUERY, include = "")
    @RequestMapping(value = "/queryLevelTypeList", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<CentreListResponse<UserLevelTypeVo>> queryLevelTypeList() throws SystemServiceException {
        DatadictCondition datadictCondition = new DatadictCondition();
        datadictCondition.setDelFlag(Constants.NOT_DELETED);
        datadictCondition.setDataDictTypeCode(Constants.UserLevelType.TYPE_DICTTYPE_CODE);
        List<DatadictPo> datadictPoList = datadictService.queryList(datadictCondition);
        List<UserLevelTypeVo> typeList = new ArrayList<>();
        datadictPoList.forEach(data -> {
            UserLevelTypeVo type = new UserLevelTypeVo();
            type.setName(data.getDataDictName());
            type.setValue(data.getDataDictValue());
            typeList.add(type);
        });
        return getSuccessResult(getListResponse(typeList));
    }

    @NeedRole("sysadminrole")
    @ApiOperation(value = "人员绑定", notes = "人员绑定", httpMethod = "POST")
    @Loggable(descp = "人员绑定", type = LogTypeEnum.SETTING, include = "")
    @RequestMapping(value = "/saveBindUserList", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity saveBindUserList(@ModelAttribute @Valid UserLevelBindUserForm userLevelBindUserForm) {
        if (userLevelBindUserForm.getId() == null) {
            return getFailResult("用户等级记录ID不能为空");
        }
        List<String> tempUserCodeList = new ArrayList<>();
        //设置人员绑定值
        if (StringUtils.isNotBlank(userLevelBindUserForm.getUserCodeList())) {
            Collections.addAll(tempUserCodeList, userLevelBindUserForm.getUserCodeList().split(Constants.SPLIT));
        }
        //查询用户等级
        UserLevelPo userLevelPo = userLevelService.query(userLevelBindUserForm.getId());
        if (userLevelPo == null) {
            return getFailResult("找不到对应的分级记录");
        }
        if (!Constants.UserLevelType.RANK.equals(userLevelPo.getLevelType())) {
            return getFailResult("人员绑定暂只支持职级");
        }
        //查询原有绑定人员记录
        UserForm userQueryFrom = new UserForm();
        userQueryFrom.setDelFlag(Constants.NOT_DELETED);
        if (Constants.UserLevelType.RANK.equals(userLevelPo.getLevelType())) {
            userQueryFrom.setUserLevel(userLevelPo.getLevelScore());
        }
        final List<UserForm> userPoList = userService.queryUser(userQueryFrom);
        final List<String> newUserCodeList = tempUserCodeList;
        //修改之前的usercode
        List<String> oldUserCodeList = userPoList.stream().map(UserForm::getUserCode).collect(Collectors.toList());
        List<String> addUserCodeList = new ArrayList<>();
        List<String> delUserCodeList = new ArrayList<>();
        //填充删除的usercode
        oldUserCodeList.forEach(data -> {
            if (!newUserCodeList.contains(data)) {
                delUserCodeList.add(data);
            }
        });
        //填充新增的usercode
        newUserCodeList.forEach(data -> {
            if (!oldUserCodeList.contains(data)) {
                addUserCodeList.add(data);
            }
        });
        //绑定用户
        UserChangeLevelForm userChangeLevelForm = new UserChangeLevelForm();
        userChangeLevelForm.setValue(userLevelPo.getLevelScore());
        userChangeLevelForm.setLevelType(userLevelPo.getLevelType());
        if (addUserCodeList != null && addUserCodeList.size() > 0) {
            userChangeLevelForm.setIfBind(true);
            userChangeLevelForm.setUserCodeList(addUserCodeList);
            userService.updateLevelAndTitile(userChangeLevelForm);
        }
        //解绑用户
        if (delUserCodeList != null && delUserCodeList.size() > 0) {
            userChangeLevelForm.setIfBind(false);
            userChangeLevelForm.setUserCodeList(delUserCodeList);
            userService.updateLevelAndTitile(userChangeLevelForm);
        }
        return getSuccessResult();
    }

    @ApiOperation(value = "查询分级类型值列表", notes = "查询分级类型值列表", httpMethod = "POST")
    @Loggable(descp = "查询分级类型值列表", type = LogTypeEnum.QUERY, include = "")
    @RequestMapping(value = "/queryLevelTypeValueList", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<CentreListResponse<UserLevelTypeValueVo>> queryLevelTypeValueList(@ApiParam(value = "类型code", required = true)
                                                                                                @RequestParam String typeCode) throws SystemServiceException {
        DatadictCondition datadictCondition = new DatadictCondition();
        datadictCondition.setDelFlag(Constants.NOT_DELETED);
        datadictCondition.setDataDictTypeCode(typeCode);
        List<DatadictPo> datadictPoList = datadictService.queryList(datadictCondition);
        List<UserLevelTypeValueVo> typeList = new ArrayList<>();
        datadictPoList.forEach(data -> {
            UserLevelTypeValueVo typeValue = new UserLevelTypeValueVo();
            typeValue.setName(data.getDataDictName());
            typeValue.setValue(Integer.valueOf(data.getDataDictValue()));
            typeList.add(typeValue);
        });
        return getSuccessResult(getListResponse(typeList));
    }

    @ApiOperation(value = "根据类型查询列表", notes = "根据类型查询列表", httpMethod = "POST")
    @Loggable(descp = "根据类型查询列表", type = LogTypeEnum.QUERY, include = "")
    @RequestMapping(value = "/queryUserLevelByLevelType", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<CentreListResponse<UserLevelVo>> queryUserLevelByLevelType(@ApiParam(value = "类型code", required = true)
                                                                                         @RequestParam String levelType) throws SystemServiceException {
        List<UserLevelPo> poList = userLevelService.queryUserLevelByLevelType(levelType);
        List<UserLevelVo> voList = CopyUtil.transfer(poList, UserLevelVo.class);
        return getSuccessResult(getListResponse(voList));
    }

    /**
     * 根据id获取用户列表
     *
     * @return
     */
    @ApiOperation(value = "根据职级/头衔获取用户ID列表", notes = "根据职级/头衔获取用户ID列表", httpMethod = "POST")
    @Loggable(descp = "根据职级/头衔获取用户ID列表", type = LogTypeEnum.QUERY, include = "")
    @RequestMapping(value = "/queryUserCodeListById", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<CentreListResponse<String>> queryUserCodeListById(@ApiParam(value = "id", required = true) @RequestParam Integer id) {
        //查出id对应数据的职级
        UserLevelPo userLevelPo = userLevelService.query(id);

        if (userLevelPo == null) {
            return getFailResult("您输入的用户信息有误");
        } else if (!Constants.UserLevelType.RANK.equals(userLevelPo.getLevelType())) {
            return getFailResult("非职级类型暂时无法绑定用户");
        }
        UserCondition condition = new UserCondition();
        condition.setDelFlag(Constants.NOT_DELETED);
        if (Constants.UserLevelType.RANK.equals(userLevelPo.getLevelType())) {
            condition.setUserLevel(userLevelPo.getLevelScore());
        }
        List<UserPo> userPoList = userService.queryList(condition);
        List<String> userCodeList = new ArrayList<>();
        if (userPoList != null && userPoList.size() > 0) {
            userCodeList = userPoList.stream().map(data -> data.getUserCode()).collect(Collectors.toList());
        }
        return getSuccessResult(getListResponse(userCodeList));
    }


    /**
     * UserLevelQueryForm转换为UserLevelCondition
     *
     * @param form
     * @return
     */
    private UserLevelCondition getConditionByQueryForm(UserLevelQueryForm form) {
        UserLevelCondition condition = CopyUtil.transfer(form, UserLevelCondition.class);
        return condition;
    }

}